<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\enterprise\model\department\Department;
use app\enterprise\model\User;
use app\model\admin\CompanyModel;
use app\model\staff\Staff;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Company extends AuthController
{
    public function list(Request $request)
    {
        $limit = $request->param('size', 10);
        $page = $request->param('page', 1);
        $name = $request->param('company_name', '');
        $status = $request->param('status', '');

        $data = CompanyModel::when($name, function ($query) use ($name) {
                $query->where('company_name', 'like', '%' . $name . '%');
            })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->order('id', 'desc')
            ->where('status', '>', 0)
            ->where('pid', 0)
            ->paginate($limit)
            ->each(function ($item) {
                $item['children'] = $this->getChildren($item['id']);
                // if ($item['create_time']) {
                //     $item['create_time'] = date('Y-m-d H:i:s', (int)$item['create_time']);
                // } else {
                //     $item['create_time'] = '';
                // }
                if ($item['expire_time']) {
                    $item['train_status'] = $item['expire_time'] > time() ? 1 : 2;
                } else {
                    $item['train_status'] = 0;
                }
                unset($item['password']);
                return $item;
            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total()
        ]);
    }
    private function getChildren($id)
    {
        $data = CompanyModel::where('status', '>', 0)
            ->where('pid', $id)
            ->select()
            ->toArray();
        foreach ($data as $key => $item) {
            $data[$key]['children'] = $this->getChildren($item['id']);
            // if ($item['create_time']) {
            //     $data[$key]['create_time'] = date('Y-m-d H:i:s', (int)$item['create_time']);
            // } else {
            //     $data[$key]['create_time'] = '';
            // }
            if ($item['expire_time']) {
                $data[$key]['train_status'] = $item['expire_time'] > time() ? 1 : 2;
            } else {
                $data[$key]['train_status'] = 0;
            }
        }
        return $data;
    }

    public function info(Request $request)
    {
        $id = input('id', '');
        $data = CompanyModel::where('id', $id)
            ->find();
        $data['password'] = '';
        return app('json')->success([
            'data' => $data
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'company_name', 'company_code', 'link_username', 'link_tel', 'has_domain', 'account',
            'domain', 'subdomain', 'file', 'pid', 'need_password', 'password', 'address',
        ]);
        $id = input('id', '');
        if ($id && (!isset($data['account']) || !$data['account'])) {
            $data['account'] = 'test';
        }
        try {
            validate([
                'company_name|企业名称' => 'require|max:120',
                'company_code|社会统一信用代码' => 'require|max:120',
                'link_username|联系人' => 'require|max:20',
                'link_tel|联系电话' => 'require|mobile',
                'account|账号' => 'require|max:30',
                'address|企业所在地' => 'max:150',
                'has_domain|开通域名' => 'require|in:1,2',
                'domain|域名' => 'requireIf:has_domain,1|max:255',
                'subdomain|域名' => 'max:255',
                'need_password' => 'require|in:1,2',
                'password|密码' => 'requireIf:need_password,1',
                'file|附件' => 'max:255',
                'pid' => 'require',
            ], [
                'need_password' => '参数错误',
                'pid.require' => '参数错误',
                'file.max' => '请上传附件'
            ])->check($data);
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        if ($data['has_domain'] == 2) {
            $data['domain'] = '';
            $data['subdomain'] = '';
        }
        unset($data['need_password']);
        if ($id) {
            $exists = CompanyModel::where('id', '<>', $id)
                ->where('status', '>', 0)
                ->where('company_name', $data['company_name'])
                ->find();
            if ($exists) {
                return app('json')->fail('企业名称已存在');
            }

            $data['update_time'] = time();
            if (isset($data['password']) && $data['password']) {
                $data['password'] = md5($data['password']);
            } else {
                unset($data['password']);
            }
            $res = CompanyModel::update($data, [
                'id' => $id
            ]);
        } else {
            $exists = CompanyModel::where('status', '>', 0)
                ->where('company_name', $data['company_name'])
                ->find();
            if ($exists) {
                return app('json')->fail('企业名称已存在');
            }

            $data['create_time'] = time();
            $data['password'] = md5($data['password']);
            Db::startTrans();
            try {
                $res = CompanyModel::create($data);
                $id = $res->id;
                // 创建部门
                $depart = Department::create([
                    'company_id' => $id,
                    'pid' => 0,
                    'department_name' => $data['company_name'],
                    'link_username' => $data['link_username'],
                    'link_mobile' => $data['link_tel'],
                ]);
                // 创建用户
                User::create([
                    'pid' => $id,
                    'company_name' => $data['company_name'],
                    'company_code' =>$data['company_code'],
                    'link_username' => $data['link_username'],
                    'link_tel' => $data['link_tel'],
                    'address' => $data['address'],
                    'file' => $data['file'],
                    'password' => $data['password'],
                    'has_domain' => $data['has_domain'],
                    'domain' => $data['domain'],
                ]);
            } catch (\Throwable $e) {
                Db::rollback();
                return app('json')->fail($e->getMessage());
            }
            Db::commit();
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        $data = CompanyModel::where('id', $id)
            ->where('status', '>', 0)
            ->find();
        if (!$id || !$data) {
            return app('json')->fail('没有可删除的数据');
        }
        $children = CompanyModel::where('pid', $id)
            ->where('status', '>', 0)
            ->find();
        if ($children) {
            return app('json')->fail('当前企业有下属企业，不可删除');
        }
        CompanyModel::update([
            'status' => -1,
            'update_time' => time(),
        ], [
            'id' => $id
        ]);
        return app('json')->success();
    }
}